import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sgy_flutter/gen/assets.gen.dart';
import 'package:sgy_flutter/model/device_model.dart';
import 'package:sgy_flutter/page/scan/view.dart';
import 'package:sgy_flutter/widget/app_dialog.dart';
import 'package:url_launcher/url_launcher.dart';

import 'logic.dart';
import 'view/device_model_view.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final logic = Get.put(HomeLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Assets.image.welcomeLogo.image(width: 100, height: 20),
        centerTitle: true,
        elevation: 0,
        actions: [
          TextButton(
            style: TextButton.styleFrom(
              foregroundColor: Colors.white,
            ),
            onPressed: () async {
              final delete = await Get.dialog(
                  AppDialog(
                    title: "提示".tr,
                    message: "是否删除所有设备".tr,
                    submit: "确定".tr,
                    cancel: "取消".tr,
                    onSubmit: () {
                      Get.backLegacy(result: true);
                    },
                  ),
                  barrierDismissible: false);
              if (delete == true) {
                logic.deleteAll();
              }
            },
            child: Text("全部删除".tr),
          )
        ],
      ),
      body: SafeArea(
        child: Column(
          children: [

            Expanded(
              child: Obx(
                () => CustomScrollView(
                  slivers: [
                    SliverList.builder(
                      itemBuilder: (BuildContext context, int index) {
                        return DeviceModelView(
                          deviceModel: logic.items[index],
                          onConnect: (DeviceModel model) {
                            if (model.inTransportMode) {
                              Get.dialog(
                                  AppDialog(
                                      title: "提示".tr,
                                      message:
                                          "功率计正处于运输模式。连接充电线进行充电，或连续转动曲柄10圈，即可退出运输模式。"
                                              .tr,
                                      submit: "确定".tr),
                                  barrierDismissible: false);
                            } else {
                              logic.connect(model);
                            }
                          },
                          onDisconnect: (DeviceModel model) {
                            logic.disconnect(model);
                          },
                          onDelete: (DeviceModel model) {
                            logic.deleteItem(model);
                          },
                          type: 1,
                        ).marginOnly(top: index == 0 ? 8 : 0);
                      },
                      itemCount: logic.items.length,
                    ),
                    SliverVisibility(
                      sliver: SliverFillRemaining(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Assets.image.iconEmpty.image(width: 120),
                            Text("您还未连接设备,请添加设备".tr)
                                .marginOnly(top: 30, left: 16, right: 16)
                          ],
                        ),
                      ),
                      visible: logic.items.isEmpty,
                    ),
                  ],
                ),
              ),
            ),
            FilledButton(
              onPressed: () async {
                final DeviceModel? model = await Get.to(() => ScanPage(), popGesture: false);
                if (model != null) {
                  logic.connect(model);
                } else {
                  logic.startScan();
                }
              },
              child: Text("添加设备".tr).paddingSymmetric(horizontal: 8),
            ),
            Obx(() => Text(
                  "${'APP版本'.tr} V${logic.appVersion}",
                  style: Get.theme.textTheme.bodySmall,
                )).marginOnly(top: 12),
            InkWell(
              onTap: () {
                final Uri _url = Uri.parse('https://www.sigeyi.com');
                launchUrl(_url);
              },
              child: Text(
                "www.sigeyi.com",
                style: Get.theme.textTheme.bodySmall?.copyWith(
                  decoration: TextDecoration.underline, // 添加下划线
                ),
              ),
            ).marginOnly(bottom: 16, top: 4)
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    Get.delete<HomeLogic>();
    super.dispose();
  }
}
